package com.myworkbench.workbench.domain.entity.resource;

import com.myworkbench.workbench.domain.common.IsDelete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 *  资源服务
 */
@Component
public class ResourceService {

   private final  ResourceRepository resourceRepository;

   @Autowired
   public ResourceService(ResourceRepository resourceRepository) {
      this.resourceRepository = resourceRepository;
   }
   /**
    *  上移下移
    * @param moveResourceId
    */
   @Transactional
   public  void move(ResourceId moveResourceId, ResourceId targetId){
      Resource movResource = this.resourceRepository.getOne(moveResourceId.getId());
      Resource targetResource = this.resourceRepository.getOne(targetId.getId());
      Integer moveNo = movResource.getIndexNo();
      Integer targetNo = targetResource.getIndexNo();
      movResource.setIndexNo(targetNo);
      targetResource.setIndexNo(moveNo);
      // 同时更新两个
      this.resourceRepository.saveAll(Arrays.asList(movResource,targetResource));
   }


   /**
    *  最大的索引号
    */
   public  Integer maxIndexNo(){
      return  resourceRepository.findMaxIndexNo(IsDelete.YES.value());
   }

   /**
    *  下一个编号
    */
   public  Integer nextIndexNo(){
      Integer currentNo = resourceRepository.findMaxIndexNo(IsDelete.YES.value());
      return  currentNo.intValue()+1;
   }
}
